//
//  ShiLiTestViewController.m
//  安好
//
//  Created by qinlongqing on 14-8-26.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "ShiLiTestViewController.h"
#import "LeftEyeViewController.h"
#import "RightEyeViewController.h"
#import "ShiLiTestResultViewController.h"
#import "CLDataBaseController.h"
#import "AFHTTPRequestOperationManager.h"
#import "Reachability.h"


@interface ShiLiTestViewController ()<UITextFieldDelegate>
{
    NSArray *charactersArray;
    
    NSMutableDictionary *testResult;
    
    UIView *enterNameView;
    
    UIView *inputUserNameView;
    
    
    CGFloat imageViewHeight;
    CGFloat titleLabelHeight;
    CGFloat goOnBTNHeight;
}
@end

@implementation ShiLiTestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self makeNavBar];
    
    if (kScreenWidth == 414) {
        imageViewHeight = 240;
        titleLabelHeight = 96;
        goOnBTNHeight = 54;
    }
    else{
        imageViewHeight = 200;
        titleLabelHeight = 80;
        goOnBTNHeight = 45;
    }
    
    CGFloat space = (kScreenHeight - 64 - imageViewHeight - titleLabelHeight - goOnBTNHeight)/4;
    
    charactersArray = [[NSArray alloc]initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z", nil];
    
    self.navigationItem.title = @"视力";
    
    [self.view setBackgroundColor:UIColorFromRGB(0x4fc1e9)];
    
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.frame = CGRectMake((kScreenWidth - imageViewHeight)/2, space, imageViewHeight, imageViewHeight);
    imageView.image = [UIImage imageNamed:@"视力测试首页"];
    [self.view addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    if (kScreenWidth == 414) {
        titleLabel.frame = CGRectMake(20, imageView.frame.origin.y + imageView.frame.size.height + space, kScreenWidth - 40, titleLabelHeight);
        titleLabel.font = [UIFont systemFontOfSize:17];
    }
    else{
        titleLabel.frame = CGRectMake(15, imageView.frame.origin.y + imageView.frame.size.height + space, kScreenWidth - 30, titleLabelHeight);
        titleLabel.font = [UIFont systemFontOfSize:15];
    }
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"请将手机屏幕面向自己，放置在距离您双眼40cm处，并保持手机屏幕的干净整洁。";
    titleLabel.numberOfLines = 3;
    titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    titleLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:titleLabel];
    
    
    UIButton *goOnBTN = [[UIButton alloc]init];
    goOnBTN.layer.cornerRadius = 3;
    if (kScreenWidth == 414) {
        goOnBTN.frame = CGRectMake(20, titleLabel.frame.origin.y + titleLabel.frame.size.height + space, kScreenWidth - 40, goOnBTNHeight);
        goOnBTN.titleLabel.font = [UIFont systemFontOfSize:22];
    }
    else{
        goOnBTN.frame = CGRectMake(15, titleLabel.frame.origin.y + titleLabel.frame.size.height + space, kScreenWidth - 30, goOnBTNHeight);
        goOnBTN.titleLabel.font = [UIFont systemFontOfSize:20];
    }
    goOnBTN.backgroundColor = [UIColor whiteColor];
    [goOnBTN setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
    [goOnBTN setTitle:@"继续" forState:UIControlStateNormal];
    [goOnBTN addTarget:self action:@selector(doGoOnBTN) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:goOnBTN];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)makeNavBar{
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(doBack)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

-(void)doBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)doGoOnBTN{
    LeftEyeViewController *leftEyeTest = [[LeftEyeViewController alloc]init];
    leftEyeTest.shiLiTestViewController = self;
    [self.navigationController pushViewController:leftEyeTest animated:YES];
}

- (void)doRightEyeTestWithLeftEyeResult:(NSString *)leftEyeResult{
    [self.navigationController popViewControllerAnimated:NO];

    RightEyeViewController *rightEyeTest = [[RightEyeViewController alloc]init];
    rightEyeTest.shiLiTestViewController = self;
    rightEyeTest.leftEyeResult = leftEyeResult;
    [self.navigationController pushViewController:rightEyeTest animated:YES];
}

- (void)doShowTestResultView{
    ShiLiTestResultViewController *shiLiTestResultViewController = [[ShiLiTestResultViewController alloc]init];
    shiLiTestResultViewController.shiLiTestViewController = self;
    shiLiTestResultViewController.testResultDict = testResult;
    [self.navigationController pushViewController:shiLiTestResultViewController animated:YES];
}

- (void)shiLiTestFinishedWithUserResult:(NSDictionary *)dict{
    testResult = [dict mutableCopy];
}

- (void)loadTestResult{
    [self.navigationController popViewControllerAnimated:NO];
    
    //判断是否登录,如果已登录：直接存入服务器。如果未登录：存入本地
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
        NSString *userName = [[UserManager shareInstance] getUserInfo].username;
        [testResult setValue:userName forKey:@"testUserName"];
        
        //1.有网  2.没网
        if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {//没网
            [self createInputTestUserNameView];
        }
        else{//有网@(kUpladTiJianTestDataURL)
            [self showActionView];
            NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"left_vision":[NSString stringWithFormat:@"%.1f",[AppConfig getShiLiLevelWithWordSize:[[testResult valueForKey:@"leftResult"] intValue]]],@"left_score":[NSString stringWithFormat:@"%ld",[AppConfig getShiLiTestScoreWithWordSize:[[testResult valueForKey:@"leftResult"] intValue]]],@"right_vision":[NSString stringWithFormat:@"%.1f",[AppConfig getShiLiLevelWithWordSize:[[testResult valueForKey:@"rightResult"] intValue]]],@"right_score":[NSString stringWithFormat:@"%ld",[AppConfig getShiLiTestScoreWithWordSize:[[testResult valueForKey:@"rightResult"] intValue]]]};
            [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kUploadShiLiTestDataURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber * statusNum = [responseObject objectForKey:@"status"];
                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                if ([statusString isEqualToString:@"0"]) {
                    alertContent([responseObject objectForKey:@"msg"]);
                }else{
                    [self doShowTestResultView];
                }
                [self hiddenActionView];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self createInputTestUserNameView];
                [self hiddenActionView];
            }];
        }
    }
    else{
        [self createInputTestUserNameView];
    }
}

- (void)createInputTestUserNameView{
    enterNameView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    enterNameView.backgroundColor = [UIColor whiteColor];
    enterNameView.alpha = 0.9;
    [self.view addSubview:enterNameView];
    
    inputUserNameView = [[UIView alloc]init];
    if (IPHONE5_OR_LATER) {
        inputUserNameView.frame = CGRectMake((kScreenWidth - 290)/2, self.view.frame.size.height - 220 - 144, 290, 144);
    }
    else{
        inputUserNameView.frame = CGRectMake((kScreenWidth - 290)/2, self.view.frame.size.height - 200 - 144, 290, 144);
    }
    inputUserNameView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:inputUserNameView];
    
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 290, 144)];
    bgImageView.image = [UIImage imageNamed:@"tijian_inputImageView"];
    [inputUserNameView addSubview:bgImageView];
    
    UILabel *bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 31, 290, 20)];
    bgLabel.textAlignment = NSTextAlignmentCenter;
    bgLabel.textColor = UIColorFromRGB(0x4fc1e9);
    bgLabel.text = @"输入你的名号";
    bgLabel.backgroundColor = [UIColor clearColor];
    [inputUserNameView addSubview:bgLabel];
    
    UIImageView *inputBg = [[UIImageView alloc]initWithFrame:CGRectMake(22, 63, 246, 40)];
    inputBg.image = [UIImage imageNamed:@"tijianjilu_inputFieldBg"];
    [inputUserNameView addSubview:inputBg];
    
    UITextField *inputField = [[UITextField alloc]init];
    inputField.frame = CGRectMake(25, 63, 240, 40);
    inputField.borderStyle = UITextBorderStyleNone;
    inputField.backgroundColor = [UIColor clearColor];
    inputField.adjustsFontSizeToFitWidth = YES;
    inputField.keyboardType = UIKeyboardTypeDefault;
    inputField.returnKeyType = UIReturnKeyDone;
    inputField.delegate = self;
    [inputField becomeFirstResponder];
    [inputUserNameView addSubview:inputField];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGRect rect = inputUserNameView.frame;
    rect.origin.y = rect.origin.y - 50;
    [UIView animateWithDuration:0.4f animations:^{
        inputUserNameView.frame = rect;
    }];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *realText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (realText && realText.length > 0)
    {
        //***获取字符串
        NSString *str=textField.text;
        //***调用关键方法，获得bool值，yes或者no：
        BOOL ok= [self isIncludeSpecialCharact:str];
        if (ok==YES) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"不能有特殊字符!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        else{
            [testResult setValue:realText forKey:@"testUserName"];
            
#pragma  记录到数据库
            [[CLDataBaseController instance] insertTableWithTestType:shiLiTest andDict:testResult];
            
            CGRect rect = inputUserNameView.frame;
            rect.origin.y = rect.origin.y + 50;
            [UIView animateWithDuration:0.4f animations:^{
                inputUserNameView.frame = rect;
                inputUserNameView.alpha = 0;
                enterNameView.alpha = 0;
            } completion:^(BOOL finished) {
                [self doShowTestResultView];
            }];
            
            [textField resignFirstResponder];
            return YES;
        }
        //***关键方法
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"内容不能为空!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    return YES;
}

-(BOOL)isIncludeSpecialCharact: (NSString *)str
{
    //***需要过滤的特殊字符：~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€。
    NSRange urgentRange = [str rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString: @"~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€"]];
    if (urgentRange.location == NSNotFound){
        return NO;
    }
    return YES;
}

- (NSMutableArray *)randomCharacters{
    NSMutableArray *tempCharactersArray = [charactersArray mutableCopy];
    NSMutableArray *selectCharactersArray = [[NSMutableArray alloc]initWithCapacity:4];
    for (int i=0; i<4; i++) {
        int j = arc4random() % (26 - i);
        [selectCharactersArray addObject:[tempCharactersArray objectAtIndex:j]];
        [tempCharactersArray removeObjectAtIndex:j];
    }
    return selectCharactersArray;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
